package com.example.demo.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demo.AppUtil.Json;
import com.example.demo.AppUtil.ImgUploadUtil;
import com.example.demo.config.ben.Qiniu;
import com.example.demo.entity.AnAttachFile;
import com.example.demo.mapper.AnAttachFileMapper;
import com.example.demo.service.IAnAttachFileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Mr.we
 * @since 2024-06-02
 */
@Service
public class AnAttachFileServiceImpl extends ServiceImpl<AnAttachFileMapper, AnAttachFile> implements IAnAttachFileService {
    @Resource
    private AnAttachFileMapper attachFileMapper;
    @Resource
    private UploadManager uploadManager;
    @Resource
    private BucketManager bucketManager;
    @Resource
    private Qiniu qiniu;
    @Resource
    private Auth auth;
    @Resource
    private ImgUploadUtil imgUploadUtil;

    public final static String NORM_MONTH_PATTERN = "yyyy/MM/";

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String uploadFile(MultipartFile file) throws IOException {
        // 获取上传文件的扩展名
        String extName = FileUtil.extName(file.getOriginalFilename());

        // 构造文件名：当前日期+随机UUID+文件扩展名
        // 采用日期和UUID组合的方式命名文件，以确保文件名的唯一性
        String fileName = DateUtil.format(new Date(), NORM_MONTH_PATTERN) + IdUtil.simpleUUID() + "." + extName;

        // 创建一个新的附件对象
        AnAttachFile attachFile = new AnAttachFile();

        // 设置附件的文件路径为构造的唯一文件名
        attachFile.setFilePath(fileName);

        // 设置附件的文件大小，以字节为单位
        attachFile.setFileSize(file.getBytes().length);

        // 设置附件的文件类型为之前获取的扩展名
        attachFile.setFileType(extName);

        // 设置附件的上传时间为当前时间
        attachFile.setUploadTime(new Date());

        if (Objects.equals(imgUploadUtil.getUploadType(), 1)) {
            // 本地文件上传
            attachFileMapper.insert(attachFile);
            return imgUploadUtil.upload(file, fileName);
        } else {
            // 七牛云文件上传
            String upToken = auth.uploadToken(qiniu.getBucket(),fileName);
            Response response = uploadManager.put(file.getBytes(), fileName, upToken);
            Json.parseObject(response.bodyString(),  DefaultPutRet.class);
            return fileName;
        }
    }

    @Override
    public void deleteFile(String fileName) {
        attachFileMapper.delete(new LambdaQueryWrapper<AnAttachFile>().eq(AnAttachFile::getFilePath,fileName));
        try {
            if (Objects.equals(imgUploadUtil.getUploadType(), 1)) {
                imgUploadUtil.delete(fileName);
            } else if (Objects.equals(imgUploadUtil.getUploadType(), 2)) {
                bucketManager.delete(qiniu.getBucket(), fileName);
            }
        } catch (QiniuException e) {
            throw new RuntimeException(e);
        }
    }
}
